package com.miaosha.ms_04.service;

import com.miaosha.ms_04.SystemConstant;
import com.miaosha.ms_04.dao.MiaoshaGoodsDao;
import com.miaosha.ms_04.dao.MiaoshaOrderDao;
import com.miaosha.ms_04.domain.*;
import com.miaosha.ms_04.exception.GlobalException;
import com.miaosha.ms_04.result.CodeMsg;
import com.miaosha.ms_04.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description //TODO
 * @Author Administrator
 * @DATE 2020/9/19 21:22
 **/
@Service
public class MiaoshaService {

    private Logger logger = LoggerFactory.getLogger(MiaoshaService.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private GoodsService goodsService;

    @Resource
    private MiaoshaOrderDao miaoshaOrderDao;

    @Resource
    private MiaoshaGoodsDao miaoshaGoodsDao;

    @Transactional
    public OrderInfo buyGoods(GoodsVo goods, User user) {
        if (user == null) {
            throw new GlobalException(CodeMsg.USER_EMPTY);
        }
        Long userId = user.getId();
        Long goodsId = goods.getId();
        if (goodsId == null) {
            throw new GlobalException(CodeMsg.GOOD_ID_EMPTY);
        }
        //校验是否该用户已经秒杀过该商品
        if (!orderService.repeatOrderByUserIdAndGoodsId(userId, goodsId)) {
            throw new GlobalException(CodeMsg.ORDER_REPEAT);
        }
        //获取商品详情
        String goodsName = goods.getGoodsName();
        //1.减去商品库存
        //1.1 修改商品库存
        System.out.println("商品库存:" + goods.getGoodsStock());
        goodsService.updateStock(goods);
        logger.info("成功减去库存，商品ID ={}", goodsId);
        //1.2 修改活动商品库存
        miaoshaGoodsDao.updateStock(goodsId);
        //2. 生成订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(1L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goodsId);
        orderInfo.setGoodsName(goodsName);
        orderInfo.setGoodsPrice(goods.getMiaoshaPrice());
        orderInfo.setOrderChannel(SystemConstant.OrderChannel.PC.getCode());
        orderInfo.setUserId(userId);
        orderInfo.setStatus(SystemConstant.OrderStatusEnum.NEW.getCode());
        orderService.insert(orderInfo);
        logger.info("----成功生成订单信息 订单ID={}", orderInfo.getId());
        //3.生成秒杀订单
        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goodsId);
        miaoshaOrder.setOrderId(orderInfo.getId());
        miaoshaOrder.setUserId(userId);
        miaoshaOrderDao.insert(miaoshaOrder);
        logger.info("----成功生成秒杀订单信息 订单ID={}", miaoshaOrder.getId());
        return orderInfo;
    }
}
